<?php
/**
 * Cube PHP Framework
 * 
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * @author Dillen / Steffen
 */

namespace Library\Mvc;
 
/**
 * @class Library.Mvc.Request 
 *
 * Request
 */
class Request
{
	/**
	 * @property {String} requestUri
	 * @var string
	 */
	public $requestUri;
	
	/**
	 * @property {String} controller
	 * @var string
	 */
	public $controller;
	
	/**
	 * @property {String} action
	 * @var string
	 */
	public $action;
	
	/**
	 * @property {Array} parameters
	 * @var array
	 */
	public $parameters = array();
	
	/**
	 * Constructor
	 * 
	 * @method __construct
	 * @param {String} [$request=null] Request string, example: controller/action/argument
	 */
	public function __construct($request = null)
	{
		$this->requestUri = $this->_cleanUri(($request == null) ? $this->_fetchUri($request) : $request);
		
		$parts = explode('/', $this->requestUri);
		
		$this->controller = array_shift($parts);
		$this->action = array_shift($parts);
		$this->parameters = (array)$parts;
	}
	
	/**
	 * Clean Uri
	 * 
	 * @method _cleanUri
	 * @private
	 * @param {String} $uri
	 * @return {String}
	 */
	private function _cleanUri($uri)
	{
		return parse_url(trim(urldecode($uri), '/'), PHP_URL_PATH);
	}
	
	/**
	 * Fetch the request uri
	 * 
	 * @method _fetchUri
	 * @private
	 * @return {String}
	 */
	private function _fetchUri()
	{
		// Check if PATH_INFO is available
		$uri = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO');
		if ($uri != '' && $uri != '/')
		{
			return $uri;
		}

		// Pick the REQUEST_URI as last resort
		$uri = $_SERVER['REQUEST_URI'];
		if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0)
		{
			$uri = substr($uri, strlen($_SERVER['SCRIPT_NAME']));
		}
		else if (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0)
		{
			$uri = substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME'])));
		}
		
		// Fix the $_GET vars
		$parts = explode('?', $uri, 2);
		$uri = $parts['0'];

		return $uri;
	}
	
	/**
	 * @method __toString
	 * @return string
	 */
	public function __toString()
	{
		return (string)$this->requestUri;
	}
}